package net.brucecooper.mindmap.client;

import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;

public class ButtonWithTooltip extends Button {

    private String tooltip;
    TooltipListener ttl = new TooltipListener();
    private PopupPanel tooltipPopup;
    
    public ButtonWithTooltip(String tooltip, String iconName) {
        super(IconManager.makeImgHTML(tooltip, iconName));
        
        this.tooltip = tooltip;
        
        addMouseOverHandler(ttl);
        addMouseOutHandler(ttl);
        addMouseMoveHandler(ttl);
    }

    private void showTooltip() {
        tooltipPopup = new PopupPanel(true);
        tooltipPopup.setStylePrimaryName("tooltip");
        tooltipPopup.setWidget(createTooltip());
        tooltipPopup.showRelativeTo(this);
        
    }
    private Widget createTooltip() {
        Label l = new Label(tooltip);
        l.addStyleName("tooltip");
        return l;
    }

    private void dismissTooltip() {
        if (tooltipPopup != null) {
            tooltipPopup.hide();
            tooltipPopup = null;
        }
    }

    

    class TooltipListener implements MouseOverHandler, MouseOutHandler, MouseMoveHandler {
        Timer t;
        
        public void onMouseOver(MouseOverEvent event) {
            startTimer();
        }
        
        private void startTimer() {
            stopTimer();
            t = new Timer() {
                @Override
                public void run() {
                    showTooltip();
                    t = null;
                }
            };
            t.schedule(750);
        }
        
        private void stopTimer() {
            if (t != null) {
                t.cancel();
                t = null;
            }
        }

        public void onMouseOut(MouseOutEvent event) {
            dismissTooltip();
            stopTimer();
        }

        public void onMouseMove(MouseMoveEvent event) {
            dismissTooltip();
            stopTimer();
            startTimer();
        }
    }


}
